<?php

namespace app\api\controller;

use app\admin\model\Login as ModelLogin;
use app\common\controller\Api;
use fast\Random;
use think\Db;

/**
 * 登录接口
 */
class Login extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 登录处理
     * 
     * @method post
     */
    public function actlogin()
    {
        $username = $this->request->post("username", '', 'trim');
        $password = $this->request->post("password", '', 'trim');
        if (empty($username)) {
            $this->error('用户名不能为空');
        }
        if (empty($password)) {
            $this->error('密码不能为空');
        }
        // 1.根据账号取出数据，取不出来数据说明没有这个用户
        // 2.根据取出的数据进行密码匹配，匹配不成功说明密码错误，重新登录 
        $memberinfo = ModelLogin::where(['username' => $username])->find();
        if (empty($memberinfo)) {
            $this->error("账号不存在");
        }
        if ($memberinfo['password'] != md5($password)) {
            $this->error("密码不正确");
        }
        // 登录成功，接口的登录验证 token(唯一字符串)
        $token = Random::uuid();
        Db::name('login_token')
            ->insert([
                'member_id' => $memberinfo['id'],
                'token' => $token,
                'createtime' => time()
            ]);
        $this->success("登录成功", ['token' => $token]);
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        session('memberinfo', null);
        $this->success("成功退出登录", 'index/index/index');
    }
}
